//import CostItem from "../controller/ui/cost_items"

import { Skill } from "../class/skill"
import { GameBalance } from "../data/GameBalance"
import DD from "../manager/dynamic_data_manager"
import JsonManager from "../manager/json_manager"
import MainManager from "../manager/main_manager"
import PoolManager from "../manager/pool_manager"
import StorageManager from "../manager/storage_manager"
import UIManager from "../manager/ui_manager"
import { Emitter } from "../utils/emmiter"
import { MessageType } from "../utils/message"
import { Utils } from "../utils/utils"


const { ccclass, property } = cc._decorator

interface OkCalBack {
    (isOK: boolean, param?: {}): void
}

@ccclass
export default class SkillDetailUIManager extends cc.Component {
    static instance: SkillDetailUIManager = null

    @property(cc.Node)
    uiNode: cc.Node = null

    @property(cc.Node)
    maskNode: cc.Node = null

    @property(cc.Label)
    labelTitle: cc.Label = null

    @property(cc.Label)
    labelDesc: cc.Label = null

    @property(cc.Button)
    btn1: cc.Button = null


   
    @property(cc.Label)
    lable1: cc.Label = null

    @property(cc.Label)
    lable2: cc.Label = null

    @property(cc.Label)
    lable3: cc.Label = null

    @property(cc.Label)
    lable4: cc.Label = null

    @property(cc.Button)
    btn2: cc.Button = null

    @property(cc.Button)
    btn3: cc.Button = null

    @property(cc.Button)
    buttonConfirm: cc.Button = null

    @property(cc.Label)
    moneyLabel: cc.Label = null

    @property(cc.Label)
    ticketLabel: cc.Label = null


    curCallBack: OkCalBack = null
    curParam: any = null
    id: string = ''

    _isClick: boolean = false

    labels: cc.Label[] = []
    level: number = 1

    @property(cc.Node)
    content1: cc.Node = null; // ScrollView 的 Content 节点

   

    onLoad() {
        // console.log("PoolManager Onload");
        SkillDetailUIManager.instance = this

        this.maskNode.on('click', this.hideUI, this);

        this.buttonConfirm.node.on("click", this.confirmUpgrade, this)
        this.labels.push(this.lable1)
        this.labels.push(this.lable2)
        this.labels.push(this.lable3)
        this.labels.push(this.lable4)
        if (this.uiNode.active) {
            this.uiNode.active = false
        }
    }



    showUI(title: string, desc: string, callback: OkCalBack = null, param: {} = null, isNormal: boolean = true, labels: string[] = null) {
        cc.log(title, desc, callback)
        cc.log(param)
        this.id = title
        if (!this.uiNode.active) {
            this.uiNode.active = true
            //  UIAnimaManager.instance.showDialog(this.uiNode, this.maskNode)
        }


        // 
        this.curParam = param
        this.refreshUI()
    }

    updateLabels(skillExtra) {
        this.clearLabels(); // 清空标签内容

        const entries = Object.entries(skillExtra); // 将对象转换为键值对数组
        let labelIndex = 1;

        for (const [key, value] of entries) {
            if (key == "id") {
                continue
            }
            let name = DD.instance.getStatName(key)
            let str=0
            if(key == 'atk'){
                str = GameBalance.calculateSkillAtk(this.id)
            }
             
            if (value !== undefined) {
                const label = this[`lable${labelIndex}`];
                if (label) {
                    label.string = `${name}: ${str} +${value}`;
                    labelIndex++;
                }
            }
            // 只处理最多 4 个标签
            if (labelIndex > 4) {
                break;
            }
        }
    }

    clearLabels() {
        this.lable1.string = "";
        this.lable2.string = "";
        this.lable3.string = "";
        this.lable4.string = "";
    }

    refreshUI() {
        let id = this.id
        let level = StorageManager.instance.skillLevel[id]
        this.level = level
        this.labelTitle.string = JsonManager.instance.getDataByName('skill')[id].name + ' Lv' + StorageManager.instance.skillLevel[id]
        // this.moneyLabel.string = StorageManager.instance.skillMoneyCost[level] + '/' + StorageManager.instance.levelInfo.money;
        this.ticketLabel.string = StorageManager.instance.remainSkillTicket + '/' + StorageManager.instance.skillTicketCost[1];

        let etrax = JsonManager.instance.getDataByName('skill_extra');
        let info = etrax[id]
        this.updateLabels(info)
        this.populateScrollView()
    }

     // 填充 ScrollView
        populateScrollView() {
            this.content1.removeAllChildren(); // 清空之前的内容
            let specidl = JsonManager.instance.getDataByName('skill_special')
            let tmp = Object.values(specidl)
            let bonusData=[]
            tmp.forEach(v=>{
                if(v.skillId == this.id){
                    bonusData.push(v)
                }
            })
            cc.log(bonusData)
            // PoolManager
            bonusData.forEach((data, index) => {
             
                let item = PoolManager.instance.createObjectByName('speicia_list_btn', this.content1)
                // 创建每一项
    
                const label = item.getComponentInChildren(cc.Label);
                if (label) {
                    label.string = `${data.desc}`;
                }
                // 设置节点名称，便于定位
                item.name = `Item-${index}`;
                if (StorageManager.instance.skillLevel[this.id]>= DD.instance.unlockMap[index+1]) {
    
                    item.getComponent(cc.Button).interactable = true
                    
                } else {
                    item.getComponent(cc.Button).interactable = false
                }
    
    
                // this.content1.addChild(item); // 添加到 Content
            });
            this.content1.getComponent(cc.Layout).updateLayout()
        }
   

    

    confirmUpgrade() {
        let level = this.level;
        let remianTick = StorageManager.instance.remainSkillTicket
        //  cc.log("money",StorageManager.instance.skillMoneyCost[level], StorageManager.instance.levelInfo.money)
         cc.log("id",this.id,"剩余",remianTick, StorageManager.instance.skillTicketCost[this.level])
        let costLevel=1
         if (
            // StorageManager.instance.levelInfo.money>=StorageManager.instance.skillMoneyCost[level]   &&
            remianTick >= StorageManager.instance.skillTicketCost[costLevel]
        ) {
            // StorageManager.instance.levelInfo.money -= StorageManager.instance.skillMoneyCost[level];
            StorageManager.instance.remainSkillTicket -= StorageManager.instance.skillTicketCost[costLevel]
            StorageManager.instance.skillLevel[this.id]++;
            StorageManager.instance.savePlayerData()
            UIManager.instance.showTip('升级成功')
            this.refreshUI()
        } else {
            UIManager.instance.showTip('资源不足')
            return false
        }


        // this.hideUI()
    }


    confirm() {

        this.hideUI()
    }
    hideUI() {
        this.uiNode.active = false
        cc.director.resume();
        //  AudioManager.instance.playAudio('ui_close')

    }
}
